package com.cheyun.netsalev3.view.cluefollowup

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.MyAdapter
import com.cheyun.netsalev3.databinding.ActivityBookingCarBinding
import com.cheyun.netsalev3.utils.BaseFragment
import com.cheyun.netsalev3.utils.ImageUploader
import com.cheyun.netsalev3.utils.ToastUtil
import com.cheyun.netsalev3.utils.UriUtils
import com.cheyun.netsalev3.viewmodel.ClueFollowUpActivityViewModel
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIItemListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.qcloud.tim.uikit.component.picture.imageEngine.impl.GlideEngine
import kotlinx.android.synthetic.main.head_layout.view.*
import java.io.File
import java.util.ArrayList

class BookingCarFragment : BaseFragment<ActivityBookingCarBinding>() {
    private val PERMISSION_CAMERA_REQUEST_CODE = 0x00000012

    private var photoUri: Uri? = null
    private var picPath: String? = null
    private val fileUri = File(Environment.getExternalStorageDirectory().path + "/photo.jpg")
    private var mCameraUri: Uri? = null   //用于保存拍照图片的uri

    private var images: ArrayList<String> = arrayListOf()

    override fun initContentView(): Int {
        return R.layout.activity_booking_car
    }

    override fun initViewModel(): ViewModel? {
        activity?.apply {
            return ViewModelProviders.of(this).get(ClueFollowUpActivityViewModel::class.java)
        }
        return super.initViewModel()
    }

    lateinit var adapter: MyAdapter
    override fun initView() {
        adapter = MyAdapter(R.layout.boo_king_car_activity_item, binding.viewModel)
        binding.recyclerView.adapter = adapter

        LiveEventBus.get()
                .with("uploadOrderImg", String::class.java)
                .observe(this, Observer {
                    if (!TextUtils.isEmpty(it)) {
                        images.add(it)
                        setImages()
                    }
                })
    }

    override fun lazyInit() {
        Log.i("BookingCarFragment","override lazyinit")
    }

    override fun initData() {
        binding.viewModel?.bookingViewData?.observe(this, Observer { list ->
            adapter.submitList(list)
        })
        binding.viewModel?.top1?.observe(this, Observer { s ->
            binding.headview?.titleText?.text = s
        })
        binding.headview?.leftBut?.setOnClickListener {
            binding.viewModel?.clickLeft(it)
        }
        binding.viewModel?.bookingBtnEnable?.observe(this, Observer {
            binding.nexBut.isEnabled = it
        })
        binding.imgAdd.setOnClickListener{
            val strings = ArrayList<String>()
            strings.add("拍摄")
            strings.add("从手机相册选择")
            DialogUIUtils.showBottomSheetAndCancel(it.context, strings, "取消", object : DialogUIItemListener() {
                override fun onItemClick(text: CharSequence, position: Int) {
                    if (position == 0) {
                        val hasCameraPermission = ContextCompat.checkSelfPermission(it.context, Manifest.permission.CAMERA)
                        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
                            //有调起相机拍照。
                            takePhone()
                        } else {
                            //没有权限，申请权限。
                            ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.CAMERA),
                                    PERMISSION_CAMERA_REQUEST_CODE)
                        }
                    } else {
                        pickPhoto()
                    }
                    println(text)
                    println(position)
                }
            }).show()
        }
        binding.imgD1.setOnClickListener{
            deleteImg(0)
        }
        binding.imgD2.setOnClickListener{
            deleteImg(1)
        }
        binding.imgD3.setOnClickListener{
            deleteImg(2)
        }
    }

    private fun takePhone() {
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 判断是否有相机
        if (captureIntent.resolveActivity(this.activity!!.getPackageManager()) != null) {
            var photoUri: Uri? = null

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                photoUri = FileProvider.getUriForFile(this.activity!!, this.activity!!.getPackageName() + ".provider", fileUri)
            } else {
                photoUri = Uri.fromFile(fileUri)
            }
            mCameraUri = photoUri
            if (photoUri != null) {
//                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                startActivityForResult(captureIntent, 1)
            }
        }
    }

    fun pickPhoto() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(intent, 2)
    }

    fun hasSdcard(): Boolean {
        val state = Environment.getExternalStorageState()
        return state == Environment.MEDIA_MOUNTED
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        // TODO Auto-generated method stub
        if (resultCode == Activity.RESULT_OK) {
            doPhoto(requestCode, data)
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    internal var time: Long? = null
    private fun doPhoto(requestCode: Int, data: Intent?) {
        if (requestCode == 1) {
            try {
                picPath = UriUtils.getTakePhotoPath(data);
                var impageUpload = ImageUploader();
                impageUpload.ossImg(context!!,picPath);
            } catch (e: Exception) {
                Log.e(TAG, e.message)
            }

        } else if (requestCode == 2) {
            if (data == null) {
                Toast.makeText(activity, "选择图片文件出错", Toast.LENGTH_LONG).show()
                return
            }
            photoUri = data.data
            if (photoUri == null) {
                Toast.makeText(activity, "选择图片文件出错", Toast.LENGTH_LONG).show()
                return
            }
            if (ContextCompat.checkSelfPermission(this.activity!!,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this.activity!!,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 2
                )
            } else {
                picPath = UriUtils.getRealPathFromUriAboveApi19(activity, photoUri)
            }

            if (picPath != null && (picPath!!.endsWith(".png") || picPath!!.endsWith(".PNG") || picPath!!.endsWith(".jpg") || picPath!!.endsWith(".JPG"))) {
                var impageUpload = ImageUploader();
                impageUpload.ossImg(context!!,picPath);
            } else {
                Toast.makeText(activity, "选择图片文件不正确", Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            1 -> {
                //调用系统相机申请拍照权限回调
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                            photoUri = Uri.fromFile(fileUri)
                        } else {
                            photoUri = FileProvider.getUriForFile(this.activity!!, this.activity!!.getPackageName() + ".provider", fileUri)
                        }
                        takephoto()
                    } else {
                        ToastUtil.toastLongMessage("设备没有SD卡！")
                    }
                } else {
                    takephoto()
                }
            }
            2//调用系统相册申请Sdcard权限回调
            -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickPhoto()
            } else {
                ToastUtil.toastLongMessage("请允许操作SDCard！！")
            }
            PERMISSION_CAMERA_REQUEST_CODE -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //允许权限，有调起相机拍照。
                    takePhone()
                } else {
                    //拒绝权限，弹出提示框。
                    Toast.makeText(activity, "拍照权限被拒绝", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    private fun takephoto() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(intent, 2)
    }


    fun deleteImg(index:Int){
        if(index>images.size-1){
            return
        }
        images.removeAt(index);
        setImages();
    }
    fun setImages(){
        for (index in 0 until images.size){
            if(index == 0) {
                GlideEngine.loadImage(binding.imgO1, Uri.parse(images[0]))
                binding.rlO1.visibility = View.VISIBLE
            }
            if(index == 1) {
                GlideEngine.loadImage(binding.imgO2, Uri.parse(images[1]))
                binding.rlO2.visibility = View.VISIBLE
            }
            if(index == 2) {
                GlideEngine.loadImage(binding.imgO3, Uri.parse(images[2]))
                binding.rlO3.visibility = View.VISIBLE
            }
        }
        for (index in images.size until 3){
            if(index == 0){
                binding.rlO1.visibility = View.GONE
            }
            if(index == 1) {
                binding.rlO2.visibility = View.GONE
            }
            if(index == 2) {
                binding.rlO3.visibility = View.GONE
            }
        }
        binding.imgAdd.visibility = if(images.size<3) View.VISIBLE else View.GONE

        binding.viewModel?.cert_images = images
    }
}
